//
//  CQPopupInfo.m
//  AppCommonUICollect
//
//  Created by ciyouzen on 2019/8/13.
//  Copyright © 2019 dvlproad. All rights reserved.
//

#import "CQPopupInfo.h"
#import <CJBaseUIKit/UIView+CJPanAction.h>
#import <Masonry/Masonry.h>

#import "CQPopupBottomToolbarContentView.h"

@interface CQPopupInfo () {
    
}

@end

@implementation CQPopupInfo

+ (CGFloat)cqCustom_screenBottomHeight {
    CGFloat screenHeight = [[UIScreen mainScreen] bounds].size.height;
    BOOL isScreenFull = screenHeight >= 812 && UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone;  // 是否是全面屏
    CGFloat screenBottomHeight = isScreenFull ?  34.0 : 0.0;    // 屏幕底部
    return screenBottomHeight;
}

#pragma mark - 从底部弹出当前视图的相关代码

#pragma mark Event
/*
 *  为clearView视图，添加顶部①下拉线Panline区域+②toolbar(没有确认按钮)
 *
 *  @param popupSuperview               弹出视图的父视图view(如果为nil，则会弹出到window上)
 *  @param clearView                    扣去顶部下拉线和顶部工具栏外的干净视图
 *  @param clearViewHeight              本视图未加上顶部下拉线和顶部工具栏前的高度
 *  @param title                        弹出视图的上部toolbar中的title
 *  @param shouldEnableTapBlank         是否允许点击空白区域（常设为YES，来实现点击空白区域来隐藏弹窗的功能）
 *  @param shouldAddPanAction           是否添加仿抖音评论的下拉拖动手势(附对于那些会弹出键盘的视图，一般设为NO，即不添加)
 *  @param popupHideHandle              关闭弹窗的执行方法
 */
+ (CQPopupInfo *)addBottom_panline_toolbarWithoutOK_inView:(nullable UIView *)popupSuperview
                                                 clearView:(UIView *)clearView
                                           clearViewHeight:(CGFloat)clearViewHeight
                                              toolbarTitle:(NSString *)title
                                      shouldEnableTapBlank:(BOOL)shouldEnableTapBlank
                                        shouldAddPanAction:(BOOL)shouldAddPanAction
                                           popupHideHandle:(void(^ _Nonnull)(void))popupHideHandle
{
    // 其他额外的顶部视图
    CQPopupBottomToolbarContentView *toolbarContentView = [[CQPopupBottomToolbarContentView alloc] initWithCustomView:clearView];
    CGFloat toolbarContentViewHeight = [CQPopupBottomToolbarContentView contentViewHeightWithCustomViewHeight:clearViewHeight];
    
    CQPopupTopView *toolbar = toolbarContentView.toolbar;
    [toolbar configToolTitle:title];
    [toolbar configCancelButtonTitle:NSLocalizedString(@"取消", nil) cancelButtonHandle:^{
        !popupHideHandle ?: popupHideHandle();
    }];
    [toolbar configOKButtonTitle:nil okButtonHandle:nil];

    
    // 执行显示弹窗的方法
    CQBottomPopupViewEdgeInsetsType edgeInsetsType = CQBottomPopupViewEdgeInsetsTypeDefault;
    CQPopupInfo *popupInfo = [CQPopupInfo addBottom_panline_inView:popupSuperview clearView:toolbarContentView clearViewHeight:toolbarContentViewHeight edgeInsetsType:edgeInsetsType tapBlankComplete:^{
        // 设置点击空白区域的方法
        if (shouldEnableTapBlank == NO) {
            return;
        }
        !popupHideHandle ?: popupHideHandle();
        
    } shouldAddPanAction:shouldAddPanAction panCompleteDismissBlock:^{
        !popupHideHandle ?: popupHideHandle();
    }];
    
    
    return popupInfo;
    
}


    
/*
 *  为clearView视图，添加顶部①下拉线Panline区域+②toolbar(有确认按钮)(可自定制点击空白区域会不会优先尝试执行确认操作，不行才执行取消操作的事件)
 *
 *  @param popupSuperview                   弹出视图的父视图view(如果为nil，则会弹出到window上)
 *  @param clearView                        扣去顶部下拉线和顶部工具栏外的干净视图
 *  @param clearViewHeight                  本视图未加上顶部下拉线和顶部工具栏前的高度
 *  @param title                            弹出视图的上部toolbar中的title
 *  @param okHandle                         确认事件(通过返回ok事件执行后所得结果及要对弹窗所做的动作来控制隐藏)
            （额外增加toolbarOKEnable参数，因为该确认事件除含toolbar的确认外，还可能要求点击空白区域时候要优先尝试执行确认操作，不行才执行取消操作的事件）
 *  @param shouldEnableTapBlank             是否允许点击空白区域（常设为YES，来实现点击空白区域来隐藏弹窗的功能）
 *  @param shouldAddPanAction               是否添加仿抖音评论的下拉拖动手势(附对于那些会弹出键盘的视图，一般设为NO，即不添加)
 *  @param tapBlankOrPandissmissFirstTryOK  点击空白区域/下拉会不会优先尝试执行确认操作，不行才执行取消操作(NO，则直接执行取消操作)
 *  @param popupHideHandle                  关闭弹窗的执行方法
 */
+ (CQPopupInfo *)addBottom_panline_toolbarWithOK_inView:(nullable UIView *)popupSuperview
                                              clearView:(UIView *)clearView
                                        clearViewHeight:(CGFloat)clearViewHeight
                                           toolbarTitle:(NSString *)title
                                               oKHandle:(CQOKResult(^ _Nonnull)(BOOL toolbarOKEnable, CQOKOperation okOperation))okHandle
                                   shouldEnableTapBlank:(BOOL)shouldEnableTapBlank
                                     shouldAddPanAction:(BOOL)shouldAddPanAction
                                     tapBlankFirstTryOK:(BOOL)tapBlankOrPandissmissFirstTryOK
                                        popupHideHandle:(void(^ _Nonnull)(void))popupHideHandle
{
    // 其他额外的顶部视图
    CQPopupBottomToolbarContentView *toolbarContentView = [[CQPopupBottomToolbarContentView alloc] initWithCustomView:clearView];
    CGFloat toolbarContentViewHeight = [CQPopupBottomToolbarContentView contentViewHeightWithCustomViewHeight:clearViewHeight];
    
    CQPopupTopView *toolbar = toolbarContentView.toolbar;
    [toolbar configToolTitle:title];
    [toolbar configCancelButtonTitle:NSLocalizedString(@"取消", nil) cancelButtonHandle:^{
        !popupHideHandle ?: popupHideHandle();
    }];
    [toolbar configOKButtonTitle:NSLocalizedString(@"完成", nil) okButtonHandle:^{
        BOOL toolbarOKEnable = YES;
        
        CQOKResult okActionResult = CQOKResultSuccessAndHide;   // ok事件执行后所得结果及要对弹窗所做的动作
        okActionResult = okHandle(toolbarOKEnable, CQOKOperationToolbarOK);
        // 对toolbarOK来说，成功则隐藏，不成功则仍然显示着弹窗
        if (okActionResult == CQOKResultSuccessAndHide || okActionResult == CQOKResultFailureAndHide) {
            !popupHideHandle ?: popupHideHandle();  // 执行取消操作
        }
    }];

    
    // 执行显示弹窗的方法
    CQBottomPopupViewEdgeInsetsType edgeInsetsType = CQBottomPopupViewEdgeInsetsTypeDefault;
    CQPopupInfo *popupInfo = [CQPopupInfo addBottom_panline_inView:popupSuperview clearView:toolbarContentView clearViewHeight:toolbarContentViewHeight edgeInsetsType:edgeInsetsType tapBlankComplete:^{
        // 设置点击空白区域的方法
        if (shouldEnableTapBlank == NO) {
            return;
        }

        if (tapBlankOrPandissmissFirstTryOK) {
            CQPopupTopView *toolbar = toolbarContentView.toolbar;
            BOOL toolbarOKEnable = toolbar.okButton.enabled;
            
            CQOKResult okActionResult = CQOKResultSuccessAndHide;   // ok事件执行后所得结果及要对弹窗所做的动作
            okActionResult = okHandle(toolbarOKEnable, CQOKOperationTapBlank);
            // 对tapBlank来说，成功则隐藏，不成功则仍然显示着弹窗
            if (okActionResult == CQOKResultSuccessAndHide || okActionResult == CQOKResultFailureAndHide) {
                !popupHideHandle ?: popupHideHandle();  // 执行取消操作
            }
            
        } else {
            !popupHideHandle ?: popupHideHandle();
        }
        
    } shouldAddPanAction:shouldAddPanAction panCompleteDismissBlock:^{
        if (tapBlankOrPandissmissFirstTryOK) {
            CQPopupTopView *toolbar = toolbarContentView.toolbar;
            BOOL toolbarOKEnable = toolbar.okButton.enabled;
            
            CQOKResult okActionResult = CQOKResultSuccessAndHide;   // ok事件执行后所得结果及要对弹窗所做的动作
            okActionResult = okHandle(toolbarOKEnable, CQOKOperationPanDismiss);
            // 对pan来说，成功不成功都要隐藏
            !popupHideHandle ?: popupHideHandle();
            
        } else {
            !popupHideHandle ?: popupHideHandle();
        }
    }];
    
    
    return popupInfo;
    
}


/*
 *  为clearView视图，添加顶部①下拉线Panline区域，并返回显示时候的frame
 *
 *  @param popupSuperview               弹出视图的父视图view(如果为nil，则会弹出到window上)
 *  @param clearView                    扣去顶部下拉线视图外的干净视图
 *  @param clearViewHeight              本视图未加上顶部下拉线前的高度
 （即使本视图最终是由其他视图包着弹出,这里也只输入本视图被干净弹出的高度,实际最终的弹窗高度,内部会自动计算后以最终高度弹出)
 *  @param edgeInsetsType               弹窗与window的(左右下)边距的类型
 *  @param tapBlankViewCompleteBlock    点击空白区域后的操作(为nil时候，点击自动隐藏，非nil时候需要自己调用隐藏)
 *  @param shouldAddPanAction           是否添加仿抖音评论的下拉拖动手势(附对于那些会弹出键盘的视图，一般设为NO，即不添加)
 *  @param panCompleteDismissBlock      拖动结束需要执行dimiss的回调(shouldAddPanAction为NO的时候，此值无效，相当于设为nil)
 *
 *  @return 视图弹出后显示的frame
 */
+ (CQPopupInfo *)addBottom_panline_inView:(nullable UIView *)popupSuperview
                                clearView:(UIView *)viewWithoutPanLine
                          clearViewHeight:(CGFloat)viewHeightWithoutPanLine
                           edgeInsetsType:(CQBottomPopupViewEdgeInsetsType)edgeInsetsType
                         tapBlankComplete:(void(^ _Nullable)(void))tapBlankViewCompleteBlock
                       shouldAddPanAction:(BOOL)shouldAddPanAction
                  panCompleteDismissBlock:(void(^ _Nullable)(void))panCompleteDismissBlock
{
    // 获取新视图
    UIView *realPopupView = [UIView new];
    realPopupView.backgroundColor = [UIColor clearColor];
    
    CGFloat panLineViewHeight;
    CGFloat toolbarTopSapcing;  // 固定拖动线的底部和其他顶部视图顶部之间的间距
    if (shouldAddPanAction) {
        panLineViewHeight = 6;
        toolbarTopSapcing = 10;
    } else {
        panLineViewHeight = 0;
        toolbarTopSapcing = 0;
    }
    
    UIView *panLineView = [UIView new];
    panLineView.layer.cornerRadius = 4;
    panLineView.layer.masksToBounds = YES;
    panLineView.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.5];
    [realPopupView addSubview:panLineView];
    [panLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(realPopupView);
        make.centerX.mas_equalTo(realPopupView);
        make.width.mas_equalTo(40);
        make.height.mas_equalTo(panLineViewHeight);
    }];
    
    [realPopupView addSubview:viewWithoutPanLine];
    [viewWithoutPanLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(realPopupView);
        make.top.equalTo(panLineView.mas_bottom).offset(toolbarTopSapcing);
        make.height.equalTo(@(viewHeightWithoutPanLine));
    }];
    
    CGFloat panLineAndSapcingHeight = panLineViewHeight+toolbarTopSapcing;
    CGFloat realPopupViewHeight = panLineAndSapcingHeight + viewHeightWithoutPanLine;
    
    // 执行显示弹窗的方法
    CJBasePopupInfo *basePopupInfo = [self cq_addBottomOnlyView:realPopupView inView:popupSuperview withHeight:realPopupViewHeight edgeInsetsType:edgeInsetsType tapBlankComplete:tapBlankViewCompleteBlock shouldAddPanAction:shouldAddPanAction panCompleteDismissBlock:panCompleteDismissBlock];
    
    CQPopupInfo *popupInfo = [[CQPopupInfo alloc] init];
    popupInfo.blankView = basePopupInfo.blankView;
    popupInfo.popupView = basePopupInfo.popupView;
    popupInfo.popupViewShowFrame = basePopupInfo.popupViewShowFrame;
    popupInfo.viewWithoutPanLine = viewWithoutPanLine;
    popupInfo.panLineAndSapcingHeight = panLineAndSapcingHeight;
//    popupInfo.viewHeightWithoutPanLine = viewHeightWithoutPanLine;
    
    return popupInfo;
}

/*
 *  将当前视图添加到window底部，并返回显示时候的frame
 *
 *  @param popupSuperview               弹出视图的父视图view(如果为nil，则会弹出到window上)
 *  @param selfHeight                   本视图被干净弹出的高度
 （即使本视图最终是由其他视图包着弹出,这里也只输入本视图被干净弹出的高度,实际最终的弹窗高度,内部会自动计算后以最终高度弹出)
 *  @param edgeInsetsType               弹窗与window的(左右下)边距的类型
 *  @param tapBlankViewCompleteBlock    点击空白区域后的操作(为nil时候，点击自动隐藏，非nil时候需要自己调用隐藏)
 *  @param shouldAddPanAction           是否添加仿抖音评论的下拉拖动手势(附对于那些会弹出键盘的视图，一般设为NO，即不添加)
 *  @param panCompleteDismissBlock      拖动结束需要执行dimiss的回调(shouldAddPanAction为NO的时候，此值无效，相当于设为nil)
 *
 *  @return 视图弹出后显示的frame
 */
+ (CJBasePopupInfo *)cq_addBottomOnlyView:(UIView *)popupView
                                   inView:(nullable UIView *)popupSuperview
                                     withHeight:(CGFloat)selfHeight
                                 edgeInsetsType:(CQBottomPopupViewEdgeInsetsType)edgeInsetsType
                               tapBlankComplete:(void(^ _Nullable)(void))tapBlankViewCompleteBlock
                             shouldAddPanAction:(BOOL)shouldAddPanAction
                        panCompleteDismissBlock:(void(^ _Nullable)(void))panCompleteDismissBlock
{
    // 设置底部位置
    UIEdgeInsets edgeInsets = UIEdgeInsetsZero;
    if (edgeInsetsType == CQBottomPopupViewEdgeInsetsTypeFloatingUp1) {
        edgeInsets = UIEdgeInsetsMake(0, 10, self.cqCustom_screenBottomHeight+10, 10);
    } else if (edgeInsetsType == CQBottomPopupViewEdgeInsetsTypeFloatingUp2) {
        edgeInsets = UIEdgeInsetsMake(0, 0, self.cqCustom_screenBottomHeight, 0);
    }
    
    
    // 设置下拉手势
    if (shouldAddPanAction) {
        [popupView cj_addPanWithPanCompleteDismissBlock:^{
            !panCompleteDismissBlock ?: panCompleteDismissBlock();
        }];
    }
    
    // 执行显示弹窗的方法
    CJBasePopupInfo *popupInfo = [CJBasePopupInfo addBottomSubviewToPopupSuperview:popupSuperview
                                                                popupView:popupView
                                                   withHeight:selfHeight
                                                   edgeInsets:edgeInsets
                                             tapBlankComplete:tapBlankViewCompleteBlock];
    
    return popupInfo;
}


@end
